import { defineStore } from 'pinia'

// 用户状态管理模块
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: {
      id: 0,
      username: '',
      name: '',
      email: '',
      role: ''
    },
    // 登录状态
    isLogin: false,
    // 权限列表
    permissions: []
  }),
  
  getters: {
    // 获取用户姓名
    getUserName: (state) => state.userInfo.name || state.userInfo.username,
    // 获取用户角色
    getUserRole: (state) => state.userInfo.role,
    // 是否已登录
    isLoggedIn: (state) => state.isLogin
  },
  
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      this.isLogin = true
    },
    
    // 设置权限列表
    setPermissions(permissions) {
      this.permissions = permissions
    },
    
    // 用户登出
    logout() {
      this.userInfo = {
        id: 0,
        username: '',
        name: '',
        email: '',
        role: ''
      }
      this.isLogin = false
      this.permissions = []
      // 清除本地存储的token
      localStorage.removeItem('access_token')
    },
    
    // 检查是否有某个权限
    hasPermission(permission) {
      return this.permissions.includes(permission)
    }
  },
  
  // 持久化配置
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['userInfo', 'isLogin']
  }
})